package com.github.pig.admin.controller.zhgl.building;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.exception.excel.ExcelImportException;
import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.admin.model.device.GuardDevice;
import com.github.pig.admin.model.entity.SysRole;
import com.github.pig.admin.model.zhgl.building.CommunityBuilding;
import com.github.pig.admin.model.zhgl.building.CommunityBuildingTree;
import com.github.pig.admin.model.zhgl.unit.BuildingUnit;
import com.github.pig.admin.service.device.IGuardDeviceService;
import com.github.pig.admin.service.sys.SysRoleService;
import com.github.pig.admin.service.zhgl.building.ICommunityBuildingService;
import com.github.pig.admin.service.zhgl.unit.IBuildingUnitService;
import com.github.pig.admin.util.AjaxJson;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.IdGenerate;
import com.github.pig.common.util.R;
import com.github.pig.common.util.UserUtils;
import com.github.pig.common.web.BaseController;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * ���ݻ�����Ϣ 前端控制器
 * </p>
 *
 * @author xiaosa
 * @since 2018-06-04
 */
@Controller
@RequestMapping("/communityBuilding")
public class CommunityBuildingController extends BaseController {
    @Autowired
    private ICommunityBuildingService communityBuildingService;
    @Autowired
    private IBuildingUnitService buildingUnitService;
    @Autowired
    private IGuardDeviceService guardDeviceService;
    @Resource
    private SysRoleService sysRoleService;

    /**
    * 通过ID查询
    *
    * @param id ID
    * @return CommunityBuilding
    */
    @GetMapping("/{id}")
    public R<CommunityBuilding> get(@PathVariable Integer id) {
        return new R<>(communityBuildingService.selectById(id));
    }

    @RequestMapping(params = "list")
    public String toIndex(ModelMap modelMap, HttpServletRequest request){
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
        modelMap.addAttribute("basePath",basePath);
        return "zhgl/building/communityBuildingList";
    }

    @RequestMapping("/upload")
    @ResponseBody
    public AjaxJson upload(ModelMap modelMap, HttpServletRequest request,String communityId){
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            try {
                Map<String ,String> map = new HashMap<>();
                List<CommunityBuilding> insertList = new ArrayList<>();
                params.setImportFields(CommunityBuilding.heads);
                List<CommunityBuilding> list = ExcelImportUtil.importExcel(file.getInputStream(),CommunityBuilding.class,params);
                if(list==null||list.size()==0){
                    j.setMsg("文件空内容。");
                    return j;
                }
                for(CommunityBuilding bean : list){
                    if(map.containsKey(bean.getBuildingName())){
                        continue;
                    }
                    if(existBuilding(bean.getBuildingName(),communityId,null)){
                        continue;
                    }
                    bean.setCommunityId(communityId);
                    map.put(bean.getBuildingName(),bean.getBuildingName());
                    if(StringUtils.isNotEmpty(bean.getBuildingType())){
                        bean.setBuildingType((CommonConstant.BUILDING_TYPE_ZHUZHAINAME.equals(bean.getBuildingType())?"0":"1"));
                    }
                    if(StringUtils.isNotEmpty(bean.getPropertyRightName())){
                        if(CommonConstant.PROPERTY_RIGHT_40.equals(bean.getPropertyRightName())){
                            bean.setPropertyRight(1);
                        }else if(CommonConstant.PROPERTY_RIGHT_50.equals(bean.getPropertyRightName())){
                            bean.setPropertyRight(2);
                        }else{
                            bean.setPropertyRight(3);
                        }

                    }
                    insertList.add(bean);
                }
                if(insertList!=null&&insertList.size()>0){
                    communityBuildingService.insertBatch(insertList);
                }

                //保存开锁信息
                List<GuardDevice> guardDeviceList = new ArrayList<>();
                for(CommunityBuilding bean : insertList){
                    GuardDevice g = new GuardDevice();
                    g.setGuardId(IdGenerate.getUUID());
                    g.setCommunityId(communityId);//当前社区ID
                    g.setGuardId(bean.getId()); //当前社区或楼宇或单元ID
                    g.setGuardPid(communityId);//当前社区或楼宇或单元的上级ID，如果是顶级，此处填字符串 0
                    g.setDeviceType("building");
                    g.setDeviceName(bean.getBuildingName());
                    g.setCreateTime(new Date());
                    g.setUpdateTime(new Date());
                    g.setDelFlag(CommonConstant.STATUS_NORMAL);
                    guardDeviceList.add(g);
                }
                if(guardDeviceList!=null&&guardDeviceList.size()>0){
                    guardDeviceService.insertBatch(guardDeviceList);
                }

                j.setMsg("成功导入："+insertList.size()+"行"+",因楼名重复失败："+(list.size()-insertList.size())+"行");
            } catch (ExcelImportException exception){
                j.setSuccess(false);
                j.setMsg("Excel模板不合法或数据格式不正确(日期格式：yyyy-MM-dd)！");
            }catch (Exception e) {
                e.printStackTrace();
                j.setSuccess(false);
                j.setMsg("文件导入失败！");
            }finally{
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }

    /**
     * 判断楼宇名称是否已经存在
     * @param buildingName
     * @return
     */
    public boolean existBuilding(String buildingName,String communityId,String id){
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("building_name",buildingName);
        entityWrapper.eq("community_id",communityId);
        if(StringUtils.isNotEmpty(id)){
            //说明是修改
            entityWrapper.ne("id",id);
        }
        entityWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
        List list = communityBuildingService.selectList(entityWrapper);
        if(list!=null&&list.size()>0){
            return true;
        }
        return false;
    }


    /**
    * 分页查询信息
    *
    * @param params 分页对象
    * @return 分页对象
    */
    @RequestMapping("/page")
    @ResponseBody
    public Page page(@RequestParam Map<String, Object> params, CommunityBuilding communityBuildingWhere) {
        EntityWrapper entityWrapper = new EntityWrapper<CommunityBuilding>();
        Claims claims = getCurrentUserInfo();
        String currentUserName = (String) claims.get("user_name");
        //根据当前用户查询所在小区
        Page<CommunityBuilding> page = new Page<CommunityBuilding>(Integer.parseInt(params.getOrDefault("page", 1).toString())
                , Integer.parseInt(params.getOrDefault("limit", 10).toString()));
        //拼装条件
        initCondition(params,entityWrapper,communityBuildingWhere);
        return communityBuildingService.selectPage(page, entityWrapper.orderBy("sort",true));
    }

    private void initCondition(Map<String, Object> params, EntityWrapper entityWrapper, CommunityBuilding communityBuildingWhere) {
        entityWrapper.eq("del_flag", CommonConstant.STATUS_NORMAL);
        if(StringUtils.isNotEmpty(communityBuildingWhere.getBuildingName())){
            entityWrapper.like("building_name",communityBuildingWhere.getBuildingName());
        }
        if(StringUtils.isNotEmpty(communityBuildingWhere.getBuildingType())){
            entityWrapper.eq("building_type",communityBuildingWhere.getBuildingType());
        }
        if(StringUtils.isNotEmpty(communityBuildingWhere.getCommunityId())){
            entityWrapper.eq("community_id",communityBuildingWhere.getCommunityId());
        }
        if(communityBuildingWhere.getPropertyRight()!=null){
            entityWrapper.eq("property_right",communityBuildingWhere.getPropertyRight());
        }
        entityWrapper.setSqlSelect("id, community_id AS communityId,(select name from community_info where id=community_id) AS communityName, building_name AS buildingName, building_type AS buildingType, (select label from sys_dict where value = building_type and type = 'building_type') AS buildingTypeName, manager, size, floor_number AS floorNumber, position, complete_date AS completeDate, developer, developer_phone AS developerPhone, cleaning_user AS cleaningUser, (select label from sys_dict where value=property_right and type = 'property_right') AS propertyRightName,property_right AS propertyRight, house_number AS houseNumber, create_time AS createTime, create_user AS createUser, update_time AS updateTime, update_user AS updateUser,sort,exist_unit as existUnit");
    }

    /**
     * 添加
     * @param  communityBuilding  实体
     * @return success/false
     */
    @RequestMapping("/doAdd")
    @ResponseBody
    public R<Boolean> add(@RequestBody CommunityBuilding communityBuilding) {
        communityBuilding.setDelFlag(CommonConstant.STATUS_NORMAL);
        R r = new R<>();
        if(existBuilding(communityBuilding.getBuildingName(),communityBuilding.getCommunityId(),null)){
            r.setData(false);
            r.setMsg("楼宇名称重复");
            return r;
        }
        communityBuildingService.insert(communityBuilding);
        //保存开锁信息
        GuardDevice g = new GuardDevice();
        g.setGuardId(IdGenerate.getUUID());
        g.setCommunityId(communityBuilding.getCommunityId());//当前社区ID
        g.setGuardId(communityBuilding.getId()); //当前社区或楼宇或单元ID
        g.setGuardPid(communityBuilding.getCommunityId());//当前社区或楼宇或单元的上级ID，如果是顶级，此处填字符串 0
        g.setDeviceType("building");
        g.setDeviceName(communityBuilding.getBuildingName());
        g.setCreateTime(new Date());
        g.setUpdateTime(new Date());
        g.setDelFlag(CommonConstant.STATUS_NORMAL);
        return new R<>(guardDeviceService.insert(g));
    }

    /**
     * 删除
     * @param id ID
     * @return success/false
     */
    @RequestMapping("/doDel")
    @ResponseBody
    public AjaxJson delete( String id) {
        AjaxJson json=new AjaxJson();
        CommunityBuilding communityBuilding = communityBuildingService.selectById(id);
        communityBuilding.setDelFlag(CommonConstant.STATUS_DEL);
        boolean flag = communityBuildingService.updateById(communityBuilding);
        json.setSuccess(flag);
        if(flag){
            json.setMsg("删除成功!");

        }else{
            json.setMsg("删除失败!");
        }
        return json;
    }

    @RequestMapping("/doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids){
        AjaxJson json=new AjaxJson();
        List<CommunityBuilding> list = communityBuildingService.selectBatchIds(Arrays.asList(ids.split(",")));
        for(CommunityBuilding bean : list){
            bean.setDelFlag(CommonConstant.STATUS_DEL);
        }
        boolean flag = communityBuildingService.updateBatchById(list);
        json.setSuccess(flag);
        if(flag){
            json.setMsg("删除成功!");

        }else{
            json.setMsg("删除失败!");
        }
        return json;
    }

    /**
     * 编辑
     * @param  communityBuilding  实体
     * @return success/false
     */
    @RequestMapping("/doUpdate")
    @ResponseBody
    public R<Boolean> edit(@RequestBody CommunityBuilding communityBuilding) {
        R r = new R();
        if(existBuilding(communityBuilding.getBuildingName(),communityBuilding.getCommunityId(),communityBuilding.getId())){
            r.setData(false);
            r.setMsg("楼宇名称重复");
            return r;
        }
        return new R<>(communityBuildingService.updateById(communityBuilding));
    }

    /**
     * 加载楼房树
     */
    @RequestMapping(params = "loadBuildingTreeData")
    @ResponseBody
    public List<CommunityBuildingTree> loadBuildingTreeData(HttpServletRequest request){
        //当前登陆人所在小区
        Claims claims = getCurrentUserInfo();
        String currentUserName = (String) claims.get("user_name");
        return communityBuildingService.initCommunityBuildingTree();
    }

    /**
     * 获取小区的楼宇信息
     *
     * @param communityId 小区标识
     * @return
     */
    @RequestMapping("/getCommunityBuildings/{communityId}")
    @ResponseBody
    public List<CommunityBuildingTree> getCommunityBuildings(@PathVariable String communityId) {
        EntityWrapper entityWrapper = new EntityWrapper<CommunityBuilding>();
        List<CommunityBuildingTree> list = new ArrayList<>();
        entityWrapper.eq("del_flag",CommonConstant.STATUS_NORMAL);
        entityWrapper.eq("community_id",communityId);
        List<CommunityBuilding> result = communityBuildingService.selectList(entityWrapper.orderBy("sort",true));
        for(CommunityBuilding communityBuilding:result){
            CommunityBuildingTree treeNode = new CommunityBuildingTree();
            treeNode.setName(communityBuilding.getBuildingName());
            treeNode.setId(communityBuilding.getId());
            treeNode.setParentId(communityId);
            treeNode.setExistUnit(communityBuilding.getExistUnit());
            list.add(treeNode);
        }
        return list;
    }

    /**
     * 获取小区的楼宇、角色信息
     *
     * @param communityId 小区标识
     * @return
     */
    @RequestMapping("/getBuildingsAndRoles/{communityId}")
    @ResponseBody
    public List<CommunityBuildingTree> getBuildingsAndRoles(@PathVariable String communityId) {
        EntityWrapper entityWrapper = new EntityWrapper<CommunityBuilding>();
        List<CommunityBuildingTree> list = new ArrayList<>();
        entityWrapper.eq("del_flag",CommonConstant.STATUS_NORMAL);
        entityWrapper.eq("community_id",communityId);
        List<CommunityBuilding> result = communityBuildingService.selectList(entityWrapper.orderBy("sort",true));
        for(CommunityBuilding communityBuilding:result){
            CommunityBuildingTree treeNode = new CommunityBuildingTree();
            treeNode.setName(communityBuilding.getBuildingName());
            treeNode.setId(communityBuilding.getId());
            treeNode.setParentId(communityId);
            treeNode.setExistUnit(communityBuilding.getExistUnit());
            list.add(treeNode);
        }
        //加载角色
        EntityWrapper roleWrapper = new EntityWrapper<SysRole>();
        roleWrapper.eq("community_id",communityId);
        roleWrapper.isNull("building_id");
        roleWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
        List<SysRole> roleList = sysRoleService.selectList(roleWrapper);
        for(SysRole sysRole : roleList){
            CommunityBuildingTree treeNode = new CommunityBuildingTree();
            treeNode.setName(sysRole.getRoleName());
            treeNode.setId(sysRole.getRoleId()+"");
            treeNode.setType("role");
            treeNode.setLeaf(true);
            treeNode.setParentId(communityId);
            list.add(treeNode);
        }
        return list;
    }

    /**
     * 获取单元信息
     *
     * @param buildingId 楼宇标识
     * @return
     */
    @RequestMapping("/getBuildingUnits/{buildingId}")
    @ResponseBody
    public List<CommunityBuildingTree> getBuildingUnits(@PathVariable String buildingId) {
        EntityWrapper entityWrapper = new EntityWrapper<CommunityBuilding>();
        List<CommunityBuildingTree> list = new ArrayList<>();
        entityWrapper.eq("del_flag",CommonConstant.STATUS_NORMAL);
        entityWrapper.eq("building_id",buildingId);
        List<BuildingUnit> result = buildingUnitService.selectList(entityWrapper.orderBy("sort",true));
        for(BuildingUnit buildingUnit:result){
            CommunityBuildingTree treeNode = new CommunityBuildingTree();
            treeNode.setName(buildingUnit.getUnitName());
            treeNode.setId(buildingUnit.getId());
            treeNode.setParentId(buildingId);
            list.add(treeNode);
        }
        return list;
    }

    /**
     * 获取单元信息
     *
     * @param buildingId 楼宇标识
     * @return
     */
    @RequestMapping("/getBuildingUnitsAndRole/{buildingId}")
    @ResponseBody
    public List<CommunityBuildingTree> getBuildingUnitsAndRole(@PathVariable String buildingId) {
        EntityWrapper entityWrapper = new EntityWrapper<CommunityBuilding>();
        List<CommunityBuildingTree> list = new ArrayList<>();
        entityWrapper.eq("del_flag",CommonConstant.STATUS_NORMAL);
        entityWrapper.eq("building_id",buildingId);
        List<BuildingUnit> result = buildingUnitService.selectList(entityWrapper.orderBy("sort",true));
        for(BuildingUnit buildingUnit:result){
            CommunityBuildingTree treeNode = new CommunityBuildingTree();
            treeNode.setName(buildingUnit.getUnitName());
            treeNode.setId(buildingUnit.getId());
            treeNode.setParentId(buildingId);
            list.add(treeNode);
        }
        //加载角色
        EntityWrapper roleWrapper = new EntityWrapper<SysRole>();
        roleWrapper.eq("building_id",buildingId);
        roleWrapper.isNull("unit_id");
        roleWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
        List<SysRole> roleList = sysRoleService.selectList(roleWrapper);
        for(SysRole sysRole : roleList){
            CommunityBuildingTree treeNode = new CommunityBuildingTree();
            treeNode.setName(sysRole.getRoleName());
            treeNode.setId(sysRole.getRoleId()+"");
            treeNode.setType("role");
            treeNode.setLeaf(true);
            treeNode.setParentId(buildingId);
            list.add(treeNode);
        }
        return list;
    }

    /**
     * 获取单元下的角色信息
     *
     * @param unitId 楼宇标识
     * @return
     */
    @RequestMapping("/getUnitRoles/{unitId}")
    @ResponseBody
    public List<CommunityBuildingTree> getUnitRoles(@PathVariable String unitId) {
        //加载角色
        List<CommunityBuildingTree> list = new ArrayList<>();
        EntityWrapper roleWrapper = new EntityWrapper<SysRole>();
        roleWrapper.eq("unit_id",unitId);
        roleWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
        List<SysRole> roleList = sysRoleService.selectList(roleWrapper);
        for(SysRole sysRole : roleList){
            CommunityBuildingTree treeNode = new CommunityBuildingTree();
            treeNode.setName(sysRole.getRoleName());
            treeNode.setId(sysRole.getRoleId()+"");
            treeNode.setParentId(unitId);
            treeNode.setType("role");
            treeNode.setLeaf(true);
            list.add(treeNode);
        }
        return list;
    }


}
